Page({
  data: {
    formError: false,
    code: -2,
    errorMessage: '用户名密码不能为空',
    username: '',
    password: '',
    remember: true,

    winWidth: 0,
    winHeight: 0,
    // tab切换  
    currentTab: 0,

    forgetpswd: '',

    //注册类型
    reg_type: 3,
    reg_name: '司机',
    regErrorMessage: '未知错误',
    regFormError: false,
    identyTime: 120,
    idenButtonWords: '获取验证码',
    identyClickdisable: false,
    sendIdenty: true,
    isAgree: true,
    notAgree: false,
    warnBarTop: 0,
    phone: '',
    identCodeOnServer: ''
  },

  checkForm: function (e) {
    var appInstance = getApp();
    var that = this;
    var object = e.detail.value;

    var pattern = /0?(13|14|15|18|17|19)[0-9]{9}/;

    if (object.username && object.password) {
      if (!pattern.test(object.username)) {
        that.setData({
          formError: true,
          errorMessage: '请输入正确的手机号'
        });

        setTimeout(function () {
          that.setData({
            formError: false,
            errorMessage: '用户名密码不能为空'
          });
        }, 3000);

        return;
      }

      console.log('username = ', object.username);
      console.log('password = ', object.password);

      wx.showToast({
        title: '正在登录...',
        icon: 'loading',
        duration: 10000
      });

      wx.request({
        url: 'https://www.lanshuicar.com/Server/LoginAPI.ashx',
        data: {
          Tel: object.username,
          password: object.password
        },
        method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        // header: {}, // 设置请求的 header
        success: function (res) {
          // success
          wx.hideToast();
          wx.clearStorageSync();

          var code = res.data.code;
          console.log(res.data)
          if (code == 0) {
            //loginSucces
            if (that.data.remember) {
              wx.setStorageSync('username', object.username);
              wx.setStorageSync('password', object.password);
              // wx.setStorageSync('password', object.password);

              //用户数据
              wx.setStorageSync('userType', res.data.data[0].USerType);
              //将全局变量isLogin置为true
              appInstance.globalData.hasLogin = true;
              //首次登陆全局变量，用来确定登陆后是否刷新订单列表
              appInstance.globalData.firstlogin = true;
              // wx.setStorageSync('cName', res.data.data[0].cName)       
              var json = res.data.data[0];
              wx.setStorageSync('userInfo', json);
              // for(var i=0,l=json.length;i<l;i++){
              //     for(var key in json[i]){
              //         console.log('key',key);
              //         wx.setStorageSync(key,json[i][key]);
              //     }
              // }
              that.getlogincode(object.username)
            } else {
              wx.clearStorageSync();
            }


            // wx.switchTab({
            //   url: '/pages/index/index',
            // })
            // var pages = getCurrentPages()
            // var backpage = pages[pages.length - 2]
            // backpage.setData({
            //   backtag: 1,
            // });

            wx.switchTab({
              url: '../index/index',
            })
            // wx.navigateBack();
            // wx.navigateTo({
            //   url: '../index/index',
            // })

          } else if (code != 0) {
            that.setData({
              formError: true,
              errorMessage: res.data.msg
            });

            setTimeout(function () {
              that.setData({
                formError: false,
                errorMessage: '用户名密码不能为空'
              });
            }, 3000);

            //登录失败之后直接清除保存
            wx.clearStorageSync();
          }
        },
        fail: function (e) {
          // fail
          console.log(e);
        },
        complete: function () {
          // complete
        }
      })
    } else {
      this.setData({
        formError: true
      });
      setTimeout(function () {
        that.setData({
          formError: false,
          errorMessage: '用户名密码不能为空'
        });
      }, 3000);
    }
  },

  forgetpswd: function () {
    wx.navigateTo({
      url: '../login/forgetpswd/forgetpswd',
    })
  },

  onShow: function () {
    var that = this
    var forgetpswd = that.data.forgetpswd
    console.log(forgetpswd)
    if (forgetpswd == '1') {
      wx.showToast({
        title: '修改成功',
        icon: 'success',
        duration: 2000
      })
    }
  },

  onLoad: function (options) {
    if (options.reg_type == 1) {
      this.setData({
        currentTab: 1,
      });
    }
    var that = this;
    var username1 = wx.getStorageSync('username');
    var password1 = wx.getStorageSync('password');

    if (username1 && password1) {
      that.setData({
        password: password1,
        username: username1,
        remember: true
      });
    }

    wx.getSystemInfo({

      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    })

    var appInstance = getApp();
    if (appInstance.globalData.identyTime > 0) {
      that.countDown();
    }
  },

  bindChanges: function (e) {
    var tab = this.data.currentTab;
    if (tab == 0) {
      // if(this.data.remember == 1){
      //   this.setData({
      //     remember : 0
      //   });
      // }else{
      //   this.setData({
      //     remember : 1
      //   });
      // }
    } else {
      if (this.data.isAgree == 1) {
        this.setData({
          isAgree: 0,
          notAgree: 1
        });
        console.log()
      } else {
        this.setData({
          isAgree: 1,
          notAgree: 0
        });
      }
    }

  },



  /** 
     * 滑动切换tab 
     */
  bindChange: function (e) {
    var that = this;
    that.setData({
      currentTab: e.detail.current
    });
  },

  /** 
   * 点击tab切换 
   */
  switchNav: function (e) {
    var that = this;

    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current
      });
    }
  },

  checkRegForm: function (e) {

    var pattern = /0?(13|14|15|18|17|19)[0-9]{9}/;

    var appInstance = getApp();
    var that = this;
    var object = e.detail.value;

    var realName = object.reg_realName;
    var companyName = object.reg_companyName;
    var username = object.reg_username;
    var password = object.reg_password;
    var identifyCode = object.reg_identifyCode;

    console.log('companyName', companyName);

    if (!realName) {
      that.showRegError('请输入您的姓名');
      return;
    }

    if (!companyName && (that.data.reg_type == 1 || that.data.reg_type == 2)) {
      companyName = '';
      that.showRegError('请输入公司名');
      return;
    }

    if (!pattern.test(username)) {
      that.showRegError('请输入正确的手机号码');
      return;
    }

    if (!password) {
      that.showRegError('请设置您的密码');
      return;
    }

    if (!identifyCode || identifyCode != that.data.identCodeOnServer) {
      that.showRegError('请输入正确的验证码');
      return;
    }

    wx.showModal({
      content: "您即将注册为" + this.data.reg_name,
      confirmText: "确定",
      cancelText: "取消",
      success: function (res) {
        if (res.confirm) {
          wx.showToast({
            title: '注册中',
            icon: 'loading',
            duration: 8000
          })

          wx.request({
            url: 'https://www.lanshuicar.com/Server/Register.ashx',
            data: {
              phone: username,
              Type: that.data.reg_type - 1,
              codeNum: identifyCode,
              Password: password,
              contact: realName,
              Method: 'Register',
              compname: companyName
            },
            method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            // header: {}, // 设置请求的 header
            success: function (res) {
              // success
              console.log(res);
              var code = res.data.code;
              if (code == 0) {
                wx.hideToast()

                wx.showToast({
                  title: '注册成功',
                  icon: 'success',
                  duration: 1500
                })

                that.setData({
                  currentTab: 0,
                });

                // that.doAfterReg(username, password)
                //手机号绑定请求
                // that.getlogincode(username)

              } else {
                that.showRegError(res.data.msg);
              }
            },
            fail: function () {
              // fail
            },
            complete: function () {
              // complete
            }
          })
        }
      }
    })
  },

  doAfterReg: function (username, password) {
    var that = this
    var appInstance = getApp()
    wx.clearStorageSync()
    wx.request({
      url: 'https://www.lanshuicar.com/Server/LoginAPI.ashx',
      data: {
        Tel: username,
        password: password
      },
      method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      // header: {}, // 设置请求的 header
      success: function (res) {
        // success
        var code = res.data.code;
        if (code == 0) {
          wx.setStorageSync('username', username);
          wx.setStorageSync('password', password);

          //用户数据
          wx.setStorageSync('userType', res.data.data[0].USerType);
          //将全局变量isLogin置为true
          appInstance.globalData.hasLogin = true;

          var json = res.data.data[0];
          wx.setStorageSync('userInfo', json);

          // var pages = getCurrentPages()
          // var backpage = pages[pages.length - 2]
          // backpage.setData({
          //   backtag: 1,
          // });

          wx.switchTab({
            url: '../index/index',
          })

        } else {
          that.showRegError(res.data.msg);
        }
      },
      fail: function () {
        // fail
        that.showRegError('网络错误');
      },
      complete: function () {
        // complete
      }
    })





    // var that = this;
    // var appInstance = getApp();
    // if(appInstance.globalData.hasLogin){


    //   wx:showModal({
    //     content: '检测到您当前已经登录，是否切换为刚刚注册的账户',
    //     confirmText: "确定",
    //     cancelText: "取消",
    //     success: function(res) {
    //       if (res.confirm) {
    //         wx.clearStorageSync();
    //         wx.request({
    //           url: 'https://www.lanshuicar.com/Server/LoginAPI.ashx',
    //           data: {
    //             Tel : username,
    //             password : password
    //           },
    //           method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    //           // header: {}, // 设置请求的 header
    //           success: function(res){
    //             // success
    //             var code = res.data.code;
    //             if(code == 0){
    //               wx.setStorageSync('username',username);
    //               wx.setStorageSync('password',password);

    //               //用户数据
    //               wx.setStorageSync('userType', res.data.data[0].USerType);
    //               //将全局变量isLogin置为true
    //               appInstance.globalData.hasLogin = true;

    //               var json = res.data.data[0];
    //               wx.setStorageSync('userInfo',json);
    //             }else{
    //               that.showRegError(res.data.msg);
    //             }
    //           },
    //           fail: function() {
    //             // fail
    //             that.showRegError('网络错误');
    //           },
    //           complete: function() {
    //             // complete
    //           }
    //         })
    //       }
    //     }
    //   });
    // }else{
    //   wx.request({
    //     url: 'https://www.lanshuicar.com/Server/LoginAPI.ashx',
    //     data: {
    //       Tel : username,
    //       password : password
    //     },
    //     method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    //     // header: {}, // 设置请求的 header
    //     success: function(res){
    //       // success
    //       var code = res.data.code;
    //       if(code == 0){
    //         wx.setStorageSync('username',username);
    //         wx.setStorageSync('password',password);

    //         //用户数据
    //         wx.setStorageSync('userType', res.data.data[0].USerType);
    //         //将全局变量isLogin置为true
    //         appInstance.globalData.hasLogin = true;
    //       }else{
    //         that.showRegError(res.data.msg);
    //       }
    //     },
    //     fail: function() {
    //       // fail
    //       that.showRegError('网络错误');
    //     },
    //     complete: function() {
    //       // complete
    //     }
    //   })
    // }
  },

  radioChange: function (e) {
    // console.log('radio发生change事件，携带value值为：', e.detail.value);
    var roleType = e.detail.value;

    switch (roleType) {
      case 'car_company':
        this.setData({
          reg_type: 1,
          reg_name: '车公司'
        });
        break;

      case 'travel_agency':
        this.setData({
          reg_type: 2,
          reg_name: '用车方'
        });
        break;

      case 'driver':
        this.setData({
          reg_type: 3,
          reg_name: '司机'
        });
        break;

      case 'guid':
        this.setData({
          reg_type: 4,
          reg_name: '导游'
        });
        break;

      case 'passenger':
        this.setData({
          reg_type: 5,
          reg_name: '乘客'
        });
        break;
    }
  },

  showRegError: function (msg) {
    var that = this;
    that.setData({
      regFormError: true,
      regErrorMessage: msg
    });

    setTimeout(function () {
      that.setData({
        regFormError: false,
        regErrorMessage: '未知错误'
      });
    }, 2000);
  },

  sendIdentify: function (e) {
    var pattern = /0?(13|14|15|18|17|19)[0-9]{9}/;
    var phone = this.data.phone;
    if (phone) {
      if (!pattern.test(phone)) {
        this.showRegError('请填写有效的手机号码');
        return;
      }
    } else {
      this.showRegError('请先填写有效的手机号码');
      return;
    }

    var that = this;
    console.log('iden', e);

    if (that.data.sendIdenty) {
      //执行发送请求验证码
      var appInstance = getApp();
      appInstance.globalData.identyTime = that.data.identyTime;
      wx.request({
        url: 'https://www.lanshuicar.com/Server/Register.ashx',
        data: {
          Method: 'GetSixRandom',
          phone: that.data.phone
        },
        method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        // header: {}, // 设置请求的 header
        success: function (res) {
          // success
          var code = res.data.code;
          console.log(res.data)
          if (code == 0) {
            that.data.identCodeOnServer = res.data.data[0].CodeNum;
            wx.showToast({
              title: '验证码发送成功',
              icon: 'success',
              duration: 2000
            });

            that.countDown();
          } else {
            that.showRegError(res.data.msg);
          }

        },
        fail: function () {
          // fail
        },
        complete: function () {
          // complete
        }
      })
    }
  },

  countDown: function () {
    var appInstance = getApp();
    var that = this;

    if (appInstance.globalData.identyTime == 0) {
      that.setData({
        idenButtonWords: "获取验证码",
        identyClickdisable: false,
      });

      return;
    }

    setTimeout(function () {
      appInstance.globalData.identyTime--;
      that.setData({
        idenButtonWords: "获取验证码(" + appInstance.globalData.identyTime + ")",
        identyClickdisable: true,
      });
      that.countDown();
    }, 1000);
  },

  srcollHandler: function (e) {
    this.setData({
      warnBarTop: e.detail.scrollTop
    });
  },

  bindInput: function (e) {
    this.data.phone = e.detail.value;
  },


  checkForm2: function (e) {
    var appInstance = getApp();
    var that = this
    var obj = e.detail.value
    var username = obj.username
    console.log(username)
    var pattern = /0?(13|14|15|18|17|19)[0-9]{9}/;
    if (!pattern.test(username)) {
      that.showError('请输入正确的手机号')
      return;
    }
    wx.showToast({
      title: '正在登录...',
      icon: 'loading',
      duration: 10000
    });
    wx.request({
      url: 'https://www.lanshuicar.com/Server/CustS/CustRgOrLogin.ashx',
      data: {
        utel: username,
      },
      method: 'GET',
      success: function (res) {
        console.log(res.data.msg)
        console.log(res.data)
        wx.hideToast()
        wx.clearStorageSync()
        if (res.data.code == 0) {
          wx.setStorageSync('username', username)
          wx.setStorageSync('password', res.data.data[0].UserPwd)
          //用户数据
          wx.setStorageSync('userType', res.data.data[0].USerType)
          //将全局变量isLogin置为true
          appInstance.globalData.hasLogin = true
          //首次登陆全局变量，用来确定登陆后是否刷新订单列表
          appInstance.globalData.firstlogin = true

          var json = res.data.data[0]
          wx.setStorageSync('userInfo', json)
          //绑定服务号openid
          that.getlogincode(username)
          wx.switchTab({
            url: '../index/index',
          })

        } else {
          that.showError(res.data.msg)
          wx.clearStorageSync();
        }

      }, fail: function (res) {
        wx.hideToast()
        that.showError(res.data.msg)
      }
    })
  },

  showError: function (msg) {
    var that = this;
    that.setData({
      formError: true,
      errorMessage: msg
    });

    setTimeout(function () {
      that.setData({
        formError: false,
        errorMessage: '未知错误'
      });
    }, 2000);
  },

  getlogincode: function (username) {
    var that = this
    var userTel = username
    wx.login({
      success: function (res) {
        var code = res.code
        console.log(code, userTel)
        that.SetUTelByCodeHdl(code, userTel)
      }
    })
  },



  SetUTelByCodeHdl: function (code, userTel) {
    // wx.showToast({
    //   title: '正在加载...',
    //   icon: 'loading',
    //   duration: 10000
    // });
    wx.request({
      url: 'https://www.lanshuicar.com/Server/Weixin/SetUTelByCodeHdl.ashx',
      data: {
        code: code,
        tel: userTel

      },
      method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      // header: {}, // 设置请求的 header
      success: function (res) {
        // success
        // var data = tool.getRegularJson(res.data);
        var code = res.data.code;
        console.log(res);
        if (code == 0) {
          console.log('post绑定请求成功')

        } else {
          console.log(res)
        }
      },
      fail: function (res) {
        console.log(res)
      },
      complete: function () {
        // wx.hideToast();
        // complete
      }
    })
  },

  callphone: function () {
    wx.makePhoneCall({
      phoneNumber: '0512-62881403' //仅为示例，并非真实的电话号码
    });
  },


})